# -*- coding: utf-8 -*-
#loading levels and stuff

import pygame
import data
import glob
import os

#hårdkodar lite leveldata
level_width = 1000
level_height = 1000

class Tile(pygame.rect.Rect):
    def __init__(self, rect, index):
        pygame.rect.Rect.__init__(self, rect)
        self.index = index


class BasicLevel:
    def __init__(self, file):
        """Set up and load a tile based level"""
        
        #We only store the tiles once, and reference them by a number
        files = glob.glob(os.path.join(data.imagedir, file + "*.png")
                
        self.bgimage, bgrect = data.load_image("tiles.png")
        
        self.player_start = (0,0)
        
        self.bg_grid = []

        self.tile_w = 100
        self.tile_h = 100
        
        while bgrect.top < level_height:
            while bgrect.left < level_width:
                self.bg_list.append(Tile(bgrect, 1))
                bgrect.left += self.tile_w
                
            bgrect.left = 0
            bgrect.top += self.tile_h
            
        
    def draw(self, camera, surface):
        """Draw the part of level that can be seen by camera,
        to surface"""
        self.draw_bg(camera, surface)
        #self.draw_fg(camera, surface)

    def get_tile(self, index, rect):
        """Return a Rect surrounding the tile in tilemap, pointed
        to by index"""
        w = rect.w / 2
        h = rect.h / 2
        
        x = index % 2 * w
        y = index // 2 * h

        return pygame.Rect(x, y, w, h)

    def draw_bg(self, camera, surface):
        """Draw the topmost layer of the parallaxing background"""
        
        to_draw = camera.collidelistall(self.bg_list)
        
        for tile in to_draw:
            rect = self.bg_list[tile]
            area = self.get_tile(rect.index, rect)
            topleft = (rect.left - camera.left, rect.top - camera.top)
            surface.blit(self.bgimage, topleft, area)
        
    
    def draw_fg(self, camera, surface):
        """Draw the topmost layer of the parallaxing background"""
        start_tile_x = (((camera[0] / self.fg_scale)
                         / self.tile_w)
                        % self.fggrid_size[0])
        start_tile_y = (((camera[1] / self.fg_scale)
                         / self.tile_h)
                        % self.fggrid_size[1])

        draw_pos = (0,0)

        for y in xrange(0, camera.height/self.tile_h):
            for x in xrange(0, camera.width/self.tile_w):
                area = self.get_tile(self.fggrid[x][y], self.fggrid_size)
                dest = (self.tile_w * x, self.tile_h * y)
                surface.blit(self.tilemap, dest, area)

